package org.jeecg.modules.cascv.image.service.merge;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.liangxianggui.LiangxiangguiApp1Service;
import org.jeecg.modules.cascv.image.util.BayerUtil;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author;作者
 * @Date 2023/2/8 9:53
 * @Description : 超冷柜
 * // 求width 和 height
 * String heightStr = dataFrames.substring(8, 12);
 * String widthStr = dataFrames.substring(12, 16);
 * int width = Integer.parseInt(widthStr, 16);
 * int height = Integer.parseInt(heightStr, 16);
 * <p>
 * 图像模式
 * String imgModel = dataFrames.substring(4, 8);
 * imageIndex.setImgModel(imgModel);
 * <p>
 * 要拍摄的图像个数 int imgNum = Integer.parseInt(dataFrames.substring(0, 4), 16);
 * 图像头包数据偏移量 int offSet = 32;
 * 时间码秒字符串 String picSecond = dataFrames.substring(10, 20);
 * 每张图需要多少包kafka数据  int stepNos = new Double(Math.ceil(width * height * 2 * 1.5 / 4012)).intValue() + 1;
 * @Version
 */
@Service
@Slf4j
public class ChaolengguiService extends ImageService {

    @Value("${imageurl}")
    private String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "6DDDH_30H,6DEDH_30H,6DFDH_30H";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if(null==lastPackageNum){
            LaptopConstant.packageNumMap.put(key,intpackageNum);
        }else {
            LaptopConstant.packageNumMap.put(key,intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (7148 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:"+intpackageNum+"，上一包包序号:"+lastPackageNum);
                }
            }
        }


        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subsecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);

        String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        String startEndFlag = conJson.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));

        startEndFlag = startEndFlag.split(";")[0];
        // dataFrames = dataFrames.substring(7,dataFrames.length()-10);
        dataFrames = dataFrames.split(";")[1].substring(2).trim();
        StringBuilder queue = LaptopConstant.imageData.get(key);


        composite(idsName, key, conJson, dataFrames, queue, startEndFlag, secondStr, subsecondStr);

        return null;
    }

    private boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue,
                              String startEndFlag, String secondStr, String subSecondStr) {


        if (LaptopConstant.START_FLAG.equalsIgnoreCase(startEndFlag) || !LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {

            if (queue == null) {
                queue = new StringBuilder();
            }
            queue.append(dataFrames);
            LaptopConstant.imageData.put(key, queue);
        } else if (LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {

            queue.append(dataFrames);
            while (queue.length() < 2592 * 1944 * 2) {
                queue.append("0");
            }
            while (queue.length() > 2592 * 1944 * 2) {
                queue.delete(queue.length() - 1, queue.length());
            }
            String imgHexStr = queue.toString();
            String heightStr = imgHexStr.substring(8, 12);
            String widthStr = imgHexStr.substring(12, 16);
            // String imgHexStr = queue.toString();
            String imgHexStr2 = imgHexStr.substring(32);

            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
                long start = System.currentTimeMillis();

                int width = Integer.parseInt(widthStr, 16);
                int height = Integer.parseInt(heightStr, 16);
                //  queue = new StringBuilder(queue.substring(0, imgSize));
                String imgModel = dataFrames.substring(4, 8);
                //imageIndex.setImgModel(imgModel);


                if (ChaoLengImgModel.VIDEO.getCode().equalsIgnoreCase(imgModel)) {
                    width = width / 4;
                    height = height / 4;
                }


//            int imgSize = new Double(width * height * 2 * 1.5).intValue();
//            if (queue.length() >= imgSize) {
//                queue = new StringBuilder(queue.substring(0, imgSize));
//            }
//            if (queue.length() < imgSize) {
//                queue.append("0");
//            }


                int[] ints = mono12p(imgHexStr2);
                int[] intarr = new int[ints.length];
                for (int i = 0; i < ints.length; i++) {
                    intarr[i] = do12to8(ints[i]);
                    intarr[i] = BayerUtil.colorToRGB(0, intarr[i], intarr[i], intarr[i]);
                }

                byte[] byteArr = new byte[intarr.length];
                for (int i = 0; i < intarr.length; i++) {
                    byteArr[i] = (byte) intarr[i];
                }

                String idStr = IdWorker.getIdStr();
                LaptopConstant.nativeImageIO.write(byteArr, height, width, "/data/images/", idStr + ".png", "png");
                String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                System.out.println("imageUrl = " + imageUrl);
                content.put("imageUrl", imageUrl);
                content.put("idsName", idsName);

                String[] split = secondStr.split(":");
                content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));

//            //将图片添加到map
//            List<JSONObject> list = LaptopConstant.infoMap.get(key);
//            if (list == null) {
//                list = new CopyOnWriteArrayList<>();
//                LaptopConstant.infoMap.put(key, list);
//            }
//            list.add(content);
//        }
                content.put("key", key);
                log.info("超冷柜"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

                return content;
            }, taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);
            LaptopConstant.imageData.remove(key);
        }


        return true;
    }

    public static void main(String[] args) {
        System.load("D:/disk1/libjpeg-9.dll");
        System.load("D:/disk1/libpng-3.dll");
        System.load("D:/disk1/NativeImageIOJNI.dll");
        //D:\pc_workspace\
        //D:\pc_workspace\数据\超冷    D:\图像数据\超冷
        List<String> strings = FileUtil.readUtf8Lines("E:\\图像数据\\cut2\\超冷\\T20230411145831_0001_0098_F1_00_6DCD_2024_0030_30_6DED_000000000.txt");
        ChaolengguiService chaolengguiService = new ChaolengguiService();
        for (String string : strings) {
            //将str转化为相应的JSONObject对象
            JSONObject jsonObject = JSONObject.parseObject(string); //6DFDH_30H  6DEDH_30H
            chaolengguiService.merge(jsonObject, "6DEDH_30H", "6DEDH_30H");
        }

    }


    private static int[] mono12p(String a) {
        if (a == null) {
            return null;
        }
        List<Long> list = new ArrayList<>();
        for (int i = 0; i + 6 <= a.length(); i = i + 6) {
            String partStr = a.substring(i, i + 6);
            char[] aChararr = partStr.toCharArray();
            StringBuilder sb1 = new StringBuilder();
            sb1.append(aChararr[3]);
            sb1.append(aChararr[0]);
            sb1.append(aChararr[1]);
            list.add(Long.parseLong(sb1.toString(), 16));

            StringBuilder sb2 = new StringBuilder();
            sb2.append(aChararr[4]);
            sb2.append(aChararr[5]);
            sb2.append(aChararr[2]);
            list.add(Long.parseLong(sb2.toString(), 16));
        }
        if (list.size() == 0) {
            return null;
        }
        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            Long b = list.get(i);
            ints[i] = Math.abs(b.intValue());
        }
        return ints;
    }

    public static int do12to8(int a) {
        double aa = a * 1.0;
        double bb = aa / 4095.0;
        aa = bb * 255.0;
        a = new Double(aa).intValue();
        return a;


    }

    public enum ChaoLengImgModel {
        ZHENG_FU("005A", "整幅模式"),
        VIDEO("0069", "视频模式"),
        KAI_CHUANG("00A5", "开窗模式");

        private final String code;
        private final String desc;

        ChaoLengImgModel(String code, String desc) {
            this.code = code;
            this.desc = desc;
        }

        public static String getDescByCode(String code) {
            for (ChaoLengImgModel e : ChaoLengImgModel.values()) {
                if (e.getCode().equalsIgnoreCase(code)) {
                    return e.getDesc();
                }
            }
            return "";
        }

        public static String getCodeByDesc(String desc) {
            for (ChaoLengImgModel e : ChaoLengImgModel.values()) {
                if (e.getDesc().equalsIgnoreCase(desc)) {
                    return e.getCode();
                }
            }
            return "";
        }

        public String getCode() {
            return code;
        }

        public String getDesc() {
            return desc;
        }
    }
}
















//                        // 生成csv 文件
//                        String imagePath = ":/data/images/" + idStr + ".png";
//                        String csvFileName = imagePath.replace(".png", ".csv");
//                        CsvWriter writer = CsvUtil.getWriter(csvFileName, Charset.forName("gbk"));
//                        for (int h = 0; h < height; h++) {
//                            String[] row = new String[width];
//                            for (int w = 0; w < width; w++) {
//                                row[w] = intarr[h * width + w] + "";
//                            }
//                            writer.write(row);
//                        }
//                        writer.flush();
//                        writer.close();
//                        LaptopConstant.chaolengFlag = true;
//                        LaptopConstant.imageData.remove(key);